package com.addcn.addcnwebview.webview;

import android.app.Activity;
import android.content.MutableContextWrapper;
import android.util.Log;
import android.webkit.WebView;


import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicReference;

/**
 * author:luwenbo
 * created on date : 2019-12-10
 * content:
 * describe:
 */
public class WebPools {
    private Object lock = new Object();
    private final Queue<WebView> mWebviews;
    private static WebPools webPools = null;
    private static final AtomicReference<WebPools> mAtomicReference = new AtomicReference<>();
    private static final String TAG = WebPools.class.getSimpleName();

    private WebPools() {
        mWebviews = new LinkedBlockingQueue<WebView>();
    }

    public static WebPools getInstance() {
        for (; ; ) {
            if (webPools != null) {
                return webPools;
            }
            if (mAtomicReference.compareAndSet(webPools, new WebPools())) {
                return webPools = mAtomicReference.get();
            }
        }
    }

    public void recycle(WebView webView) {
        recycleInternal(webView);
    }

    public WebView acquireWebView(Activity activity) {
        return acquireWebViewInternal(activity);
    }

    private WebView acquireWebViewInternal(Activity activity) {
        WebView mWebView = mWebviews.poll();
        Log.i(getClass().getName(),"acquireWebViewInternal  webview:" + mWebView);
        if (mWebView == null) {
            synchronized (lock) {
                return new WebView(new MutableContextWrapper(activity));
            }
        } else {
            MutableContextWrapper mMutableContextWrapper = (MutableContextWrapper) mWebView.getContext();
            mMutableContextWrapper.setBaseContext(activity);
            return mWebView;
        }
    }

    private void recycleInternal(WebView webView) {
        try {
            if (webView.getContext() instanceof MutableContextWrapper) {
                MutableContextWrapper mContext = (MutableContextWrapper) webView.getContext();
                mContext.setBaseContext(mContext.getApplicationContext());
                Log.i(getClass().getName(),"enqueue  webview:" + webView);
                mWebviews.offer(webView);
            }
            if (webView.getContext() instanceof Activity) {
                //throw new RuntimeException("leaked");
                Log.i(getClass().getName(),"Abandon this webview  ， It will cause leak if enqueue !");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
